import {compose, lifecycle, withHandlers, withState} from "recompose"
import {get, OK, postParam} from "../../shared/server"

let appUnmount = false

const appCompose = compose(
  withState('menuCollapsed', '$menuCollapsed', false),
  withState('userInfo', 'setUserInfo', {name: '杰兰特', role: '超级管理员'}),
  withState('userInfoBusy', '$userInfoBusy', false),
  withHandlers({
    setMenuCollapsed: ({$menuCollapsed}) => {
      return (value) => {
        const body = document.getElementsByTagName("body")[0]
        if (body) {
          if (value) {
            body.classList.add('collapsed')
            body.classList.remove('expanded')
          } else {
            body.classList.add('expanded')
            body.classList.remove('collapsed')
          }
        }
        $menuCollapsed(value)
      }
    },
    getUserInfo: ({setUserInfo, $userInfoBusy}) => {
      return () => {
        $userInfoBusy(true)
        get('/management/info')
          .then((data) => {
            setUserInfo(Object.assign({}, data))
            //保存头像到本地
            // localStorage.setItem(`${data.userName}_avatar`, data.avatar)
            // localStorage.setItem(`${data.phoneNo}_avatar`, data.avatar)
            $userInfoBusy(false)
          })
          .catch(error => {
          })
          .finally(() => $userInfoBusy(false))
      }
    },
    logout: ({history}) => {
      return () => {
        postParam('/management/logout')
          .then((data) => {
            if (data.code === OK) {
              history.push('/login')
            }
          })
      }
    }
  }),
  lifecycle({
    componentDidMount() {
      appUnmount = false
      const {getUserInfo} = this.props
      getUserInfo()
      const body = document.getElementsByTagName("body")[0]
      if (body) {
        body.classList.add('expanded')
        body.classList.remove('collapsed')
      }
    },
    componentWillUnmount() {
      appUnmount = true
    }
  })
)

export default appCompose
